package model

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"runtime"
	"time"
)

// HealthResponse 健康检查响应结构
type HealthResponse struct {
	Status    string    `json:"status"`
	Timestamp time.Time `json:"timestamp"`
	Version   string    `json:"version"`
	Uptime    string    `json:"uptime"`
	System    struct {
		GoVersion string `json:"go_version"`
		OS        string `json:"os"`
		Arch      string `json:"arch"`
		NumCPU    int    `json:"num_cpu"`
	} `json:"system"`
}

// StartTime 记录服务启动时间
var StartTime = time.Now()

func (api *Server) Api() {
	api.Run.GET("/api", func(c *gin.Context) {
		// 获取客户端IP地址
		// 如果有代理服务器，会返回代理服务器的IP
		clientIP := c.ClientIP()

		// 检查是否有X-Forwarded-For头
		if forwardedFor := c.GetHeader("X-Forwarded-For"); forwardedFor != "" {
			// 如果有，使用X-Forwarded-For头中的IP地址
			clientIP = forwardedFor
		}

		// 返回JSON响应
		c.String(http.StatusOK, clientIP)
	})
}

type Res struct {
	Code int    // 代码
	Msg  string // 信息
	Ip   string // 访客IP地址
}

func (api *Server) ApiJson() {
	api.Run.GET("/json", func(c *gin.Context) {
		// 获取客户端IP地址
		// 如果有代理服务器，会返回代理服务器的IP
		clientIP := c.ClientIP()
		res := new(Res)
		res.Msg = "你使用了公网访问"
		res.Code = http.StatusOK
		// 检查是否有X-Forwarded-For头
		if forwardedFor := c.GetHeader("X-Forwarded-For"); forwardedFor != "" {
			// 如果有，使用X-Forwarded-For头中的IP地址
			clientIP = forwardedFor
			res.Msg = "你使用了代理/Nat转换请求"
		}
		res.Ip = clientIP

		// 返回JSON响应
		c.JSON(http.StatusOK, res)
	})
}

// HealthCheck 健康检查接口
func (api *Server) HealthCheck() {
	api.Run.GET("/health", func(c *gin.Context) {
		response := HealthResponse{
			Status:    "healthy",
			Timestamp: time.Now(),
			Version:   "1.0.0",
			Uptime:    time.Since(StartTime).String(),
		}

		// 系统信息
		response.System.GoVersion = runtime.Version()
		response.System.OS = runtime.GOOS
		response.System.Arch = runtime.GOARCH
		response.System.NumCPU = runtime.NumCPU()

		c.JSON(http.StatusOK, response)
	})
}

// ReadinessCheck 就绪检查接口
func (api *Server) ReadinessCheck() {
	api.Run.GET("/ready", func(c *gin.Context) {
		c.JSON(http.StatusOK, gin.H{
			"status":    "ready",
			"timestamp": time.Now(),
			"service":   "ip-service",
		})
	})
}
